---
title: Form
description: Building forms with React Hook Form and Zod.
shadcnDocsLink: https://ui.shadcn.com/docs/components/form
---

<ComponentPreview component="form">
  ```tsx file=<rootDir>/src/examples/ui/form.tsx
  ```
</ComponentPreview>

## Installation

<Installation component="form">
  ```tsx file=<rootDir>/src/components/ui/form.tsx
  ```
</Installation>

## Usage

```ts
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { z } from 'zod'

import { Button } from '@/components/ui/button'
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
```

```ts
const formSchema = z.object({
  username: z.string().min(2, {
    message: 'Username must be at least 2 characters.',
  }),
})

const form = useForm<z.infer<typeof formSchema>>({
  resolver: zodResolver(formSchema),
  defaultValues: {
    username: "",
  },
});

function onSubmit(values: z.infer<typeof formSchema>) {
  console.log(values);
}
```

```tsx
<Form {...form}>
  <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
    <FormField
      control={form.control}
      name="username"
      render={({ field }) => (
        <FormItem>
          <FormLabel>Username</FormLabel>
          <FormControl>
            <Input placeholder="ekmas" {...field} />
          </FormControl>
          <FormDescription>This is your public display name.</FormDescription>
          <FormMessage />
        </FormItem>
      )}
    />
    <Button type="submit">Submit</Button>
  </form>
</Form>
```